package com.market.domain.strategy.service.armory;


import com.market.domain.strategy.model.entity.StrategyAwardEntity;
import com.market.domain.strategy.model.entity.StrategyEntity;
import com.market.domain.strategy.model.entity.StrategyRuleEntity;
import com.market.domain.strategy.repository.IStrategyRepository;
import com.market.types.common.Constants;
import com.market.types.enums.ResponseCode;
import com.market.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.SecureRandom;
import java.util.*;

@Service
@Slf4j
//策略装配库（兵工厂）。 负责初始化策略计算
public class StrategyArmoryDispatch implements IStrategyArmory, IStrategyDispatch{

    @Resource
    private IStrategyRepository repository;

    @Override
    //装配概率表
    public boolean assembleLotteryStrategy(Long strategyId) {

        //1. 正常查询策略配置奖品id
        List<StrategyAwardEntity> strategyAwardList = repository.queryStrategyAwardList(strategyId);

        //2.缓存奖品库存，由于decr扣减库存使用
        for(StrategyAwardEntity strategyAward : strategyAwardList){
            Integer awardId = strategyAward.getAwardId();
            //获取的是总库存,不是剩余库存
            Integer awardCount = strategyAward.getAwardCount();
            cacheStrategyAwardCount(strategyId, awardId, awardCount);
        }

        //3.1 装配默认策略配置
        assembleLotteryStrategy(String.valueOf(strategyId), strategyAwardList);

        //3.2.权重查询策略配置（如花费积分4000以上：102-105,5000以上：102-106）见strategy_rule表中rule_weight数据行
        //先插策略，
        StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        //再查权重
        String ruleWeight = strategyEntity.getRuleWeight();

        //若策略没配置权重
        if(ruleWeight == null)
            return true;

        //查询
        StrategyRuleEntity strategyRuleEntity = repository.queryStrategyRule(strategyId, ruleWeight);
        if(strategyRuleEntity == null){
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(), ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }
        //判断权重的奖品集合是否和默认一样
        Map<String, List<Integer>> ruleWeightValueMap = strategyRuleEntity.getRuleWeightValues();
        Set<String> keys = ruleWeightValueMap.keySet();
        for(String key : keys){
            List<Integer> ruleWeightValues = ruleWeightValueMap.get(key);
            ArrayList<StrategyAwardEntity> strategyAwardListClone = new ArrayList<>(strategyAwardList);
            //删掉克隆数组中不存在于权重集合中的奖品
            strategyAwardListClone.removeIf(strategyAward -> !ruleWeightValues.contains(strategyAward.getAwardId()));

            //配置该权重奖品的map
            assembleLotteryStrategy(String.valueOf(strategyId).concat( "_").concat( key), strategyAwardListClone);
        }


        return true;
    }

    @Override
    public boolean assembleLotteryStrategyByActivityId(Long activityId) {
        Long strategyId = repository.queryStrategyIdByActivityId(activityId);
        return assembleLotteryStrategy(strategyId);
    }

    private void cacheStrategyAwardCount(Long strategyId, Integer awardId, Integer awardCount) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        repository.cacheStrategyAwardCount(cacheKey, awardCount);
    }

    //参数：策略id，以及上个方法中存在redis中的奖品id
    private void assembleLotteryStrategy(String key, List<StrategyAwardEntity> strategyAwardList){

        //1.拿到最小概率值
        Float minAwardRate = strategyAwardList.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .min(Float::compareTo)
                .orElse(0.0f);

        //2.获取概率值总和
        Float sumAwardRate = strategyAwardList.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .reduce(0.0f, Float::sum);

        //3.计算概率值
        //1 % 0.0001 获取概率范围：百分位，千分位，万分位
        //向上取整，得到范围值
        Integer rateRange = (int) Math.ceil(sumAwardRate / minAwardRate);

        //4. 生成策略
        ArrayList<Integer> strategyAwardSearchRateTables = new ArrayList<>(rateRange);
        for(StrategyAwardEntity strategyAward : strategyAwardList){
            Integer awardId = strategyAward.getAwardId();
            Float awardRate = strategyAward.getAwardRate();

            //计算该奖品的概率占多少空间，循环填充，有多少个概率值，就会填充多少个奖品
            for(int i = 0; i < (int) Math.ceil(rateRange * awardRate); i++){
                strategyAwardSearchRateTables.add(awardId);
            }
        }

        //5. 乱序
        Collections.shuffle(strategyAwardSearchRateTables);

        //6. 存到map中
        HashMap<Integer, Integer> shuffleStrategyAwardSearchRateTables = new HashMap<>();
        for(int i = 0; i < strategyAwardSearchRateTables.size(); i++){
            shuffleStrategyAwardSearchRateTables.put(i, strategyAwardSearchRateTables.get(i));
        }

        //7. 存到redis中
        repository.storeStrategyAwardSearchRateTables(key, rateRange, shuffleStrategyAwardSearchRateTables);
    }

    @Override
    public Integer getRandomAwardId(Long strategyId) {

        //获取值
        int rateRange = repository.getRateRange(strategyId);
        //通过概率表查找中奖信息
        return repository.getStrategyAwardAssemble(String.valueOf(strategyId), new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Integer getRandomAwardId(Long strategyId, String ruleWeightValue) {

        String key = String.valueOf(strategyId).concat(Constants.UNDERLINE).concat(ruleWeightValue);
        //获取值
        int rateRange = repository.getRateRange(key);
        //通过概率表查找中奖信息
        return repository.getStrategyAwardAssemble(key, new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Boolean subtractionAwardStock(Long strategyId, Integer awardId, Date endDateTime) {

        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        return repository.subtractionAwardStock(cacheKey, endDateTime);
    }
}
